/* 验证码登录页 */

import api from '../../../utils/http.js'
import create from '../../../utils/create'
import store from '../../../store'

var WebIM = require('../../../utils/WebIM.js').default

create(store, {
  data: {
    phone: '',  //手机号码
    send: false, //验证码获取与否
    second: 60, //倒计时
    btnBright: true, //登录按钮是否高亮
    verification_key: '', 
    verification_code: '',
    dialogFlag: false
  },

  // 输入手机号
  handleInput(e){
    this.setData({phone: e.detail.value})
  },  

  // 输入验证码
  handleCode(e) { 
    if(e.detail.value.length === 4){
      this.setData({
        btnBright: false,
        verification_code: e.detail.value
      }) 
    }else{
      this.setData({btnBright: true})
    }
  }, 

  // 发送验证码
  sendCaptcha() {
    if(this.data.phone === ''){
      wx.showToast({title: '手机号码不能为空',icon: 'none'});
        return false
    }
    if(!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.data.phone)){
      wx.showToast({title: '手机号码格式错误',icon: 'none'});
        return false
    }

    api.verificationCode({phone: this.data.phone}).then(res => {
      console.log('发送验证码', res)

      this.setData({send: true, verification_key: res.data.data.key,})

      this.timer()
    })
  },

  // 倒计时
  timer() {
    new Promise((resolve, reject) => {
      let setTimer = setInterval(() => {
        this.setData({second: this.data.second - 1})

        // 倒计时结束复位并取消计时器
        if (this.data.second <= 0) {
          this.setData({second: 60,send: false})

          resolve(setTimer)
        }
      }, 1000)
    }).then((setTimer) => { clearInterval(setTimer) })
  },
 
  // 登录 
  submit() {
    if(!this.data.send){
      wx.showToast({title: '请先获取验证码',icon: 'none'})
      return false
    }

    // 手机号注册用户或者登陆
    api.phoneLogin({ verification_key: this.data.verification_key, verification_code: this.data.verification_code }).then(res => {
      console.log('手机号注册用户或者登陆', res)
      
      if (res.statusCode === 200) {
        let { access_token, user } = res.data.data

        // 注册环信账号
        var options = {
          apiUrl: WebIM.config.apiURL,
          username: user.id, //用id作为用户名
          password: '123456',
          nickname: "",
          appKey: WebIM.config.appkey,
          success() { 
            console.log('环信账号注册成功') 
          },
          error(err) { 
            console.log('该环信账号已经被注册') 
          }
        }
        WebIM.utils.registerUser(options)

        // 将token、用户id和用户头像存到本地缓存
        wx.setStorage({key: 'token', data: access_token})
        wx.setStorage({key: 'userId', data: user.id})
        wx.setStorage({ key: 'myAvatar', data: user.avatar})
        wx.setStorage({key: 'phone', data: this.data.phone})
        
        let userInfo = wx.getStorageSync('userInfo')
        if(userInfo){
          // 编辑用户资料
          api.edit({nickname: userInfo.nickName, gender: userInfo.gender, avatar: userInfo.avatarUrl}).then(res => {
            console.log('更新授权过后的用户信息', res);
          })
        }

        this.update({dialogFlag: true})

        setTimeout(() => { wx.reLaunch({ url: '/pages/home/home', }) }, 500)

      } else {
        wx.showToast({title: res.data.message,icon: 'none'})
      }
    })
  },
})